import React, { Component } from "react";
import { Button, message, Modal, Table, Divider } from "antd";
import { InfoCircleTwoTone, FileExcelOutlined } from "@ant-design/icons";
import { importsExcel } from "./InOutExcel";
import axios from "axios";
import qs from "qs";
import "../mock/importExcelDatas";

export default class ImportExportExcel extends Component {
  // formRef = React.createRef();

  constructor(props) {
    super(props);
    this.state = {
      addVisible: false,
      confirmLoading: false,
      dataSource: [],
    };
    // 模板下载事件
    this.jumpTo = this.jumpTo.bind(this);
    this.formRefArr = [];
    this.columns = [
      {
        title: "日期",
        dataIndex: "meetingDate",
        key: "meetingDate",
        width: 120,
      },
      {
        title: "事件内容",
        dataIndex: "theme",
        key: "theme",
      },
      {
        title: "时间",
        dataIndex: "meetingTime",
        key: "meetingTime",
        width: 110,
        render: (enable, record) => (
          <>
            {record.meetingTime}-{record.meetingEndTime}
          </>
        ),
      },
      {
        title: "地点",
        dataIndex: "locale",
        key: "locale",
        width: 150,
      },
      {
        title: "出席领导",
        dataIndex: "meetingLeaders",
        key: "meetingLeaders",
        width: 100,
      },
      {
        title: "责任部门",
        dataIndex: "responsibleDepartment",
        key: "responsibleDepartment",
        width: 120,
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
        ellipsis: true,
        width: 150,
      },
    ];
  }
  showAddModal = () => {
    this.setState({
      addVisible: true,
    });
  };

  //   模板下载;
  jumpTo() {
    window.open(this.props.templateHref);
  }

  // 导出Excel表格
  exportExcel() {
    const url = this.props.downloadUrl;
    window.open(url);
  }
  /**处理表格数据 */
  getExcelData = (e) => {
    importsExcel(e).then(
      (data) => {
        // console.log(data);
        let item = {};
        let excel = data.map((line) => {
          item = { ...item, ...line };
          return {
            meetingDate: item.日期,
            meetingTime: item.时间.split("-")[0],
            meetingEndTime: item.时间.split("-")[1],
            locale: item.地点,
            theme: item.事件内容,
            remark: item.备注,
            responsibleDepartment: item.责任部门,
            meetingLeaders: item.出席领导,
          };
        });
        console.log(excel);
        this.setState({ dataSource: excel });
        // actionList(data);
      },
      function (data) {
        console.log(data);
      }
    );
  };

  /**取消导入，关闭对话框 */
  handleCancel = () => {
    /**清空修改表单状态 */
    this.setState({
      addVisible: false,
      dataSource: [],
      confirmLoading: false,
    });
  };

  /**确认导入 */
  uploadExcel = () => {
    /**导入表格 */
    if (this.state.dataSource.length) {
      this.setState({
        confirmLoading: true,
      });
      axios
        .post(
          "../weekmeeting/importExcelDatas.rst",
          qs.stringify({ data: JSON.stringify(this.state.dataSource) })
        )
        .then((res) => {
          let response = res.data;
          // console.log(response);
          if (response.resultCode === 0) {
            let data = response.result.data;
            if (data.length === 0) {
              /**没有重名 */
              this.setState({
                confirmLoading: false,
                addVisible: false,
              });
              message.success("数据导入成功");
              this.props.getDataSource();
            } else {
              /**弹出提示框 */
              let notic = "出席领导匹配失败";
              const noticeModal = Modal.info({
                title: notic,
                content: (
                  <>
                    {data.map((item) => {
                      if (item.leaders) {
                        return (
                          <>
                            <Divider />
                            事件 “<span className="blue">{item.theme}</span>”
                            中，领导 “
                            <span className="blue">{item.leaders}</span>”
                            与已有领导无法匹配，您可手动修改此会议。
                          </>
                        );
                      }
                      return null;
                    })}
                  </>
                ),
                onOk: () => {
                  this.setState({
                    confirmLoading: false,
                    addVisible: false,
                  });
                  this.props.getDataSource();
                },
              });
            }
          } else {
            message.error("数据导入失败");
          }
        })
        .catch((error) => {
          console.log(error);
          message.error("数据导入失败");
        });
    } else {
      message.warning("请先上传表格");
    }
  };

  render() {
    const { addVisible, dataSource, confirmLoading } = this.state;
    return (
      <>
        {/* <Button type="primary" key="exportExcel" onClick={this.exportExcel}>
          导出
        </Button> */}
        <Button type="primary" onClick={this.showAddModal}>
          <FileExcelOutlined />
          导入
        </Button>
        <Modal
          /**对话框属性 */
          visible={addVisible}
          title="导入活动"
          centered
          onCancel={this.handleCancel}
          width={1000}
          onOk={this.uploadExcel}
          confirmLoading={confirmLoading}
          okText="导入"
          cancelText="取消"
          destroyOnClose={true}
          keyboard={false}
        >
          <input
            type="file"
            accept=".xls,.xlsx"
            onChange={(e) => {
              this.getExcelData(e);
            }}
          />
          <InfoCircleTwoTone style={{ fontSize: "21px", margin: "7px" }} />
          <span>如预览中数据有误，请检查字段后再重新上传</span>
          <Divider />
          <p>
            注：为避免识别错误，需要将首行表头字段固定为：日期、事件内容、地点、时间、责任部门、出席领导、备注，几个字段。
            日期字段格式为 yyyy-mm-dd ，月份不满10的需补‘0’，避免使用中文字符。
            时间字段格式为 HH:MM
            ，使用24小时制，避免使用中文字符。单元格无内容时，可填入“空格”或“无”，避免单元格为空
          </p>
          <Table
            dataSource={dataSource}
            columns={this.columns}
            bordered
            scroll={{ y: 350 }}
            pagination={false}
          />
        </Modal>
      </>
      // <Button style={{marginLeft: 10}} key='templateDowload' onClick={this.jumpTo}>模板下载</Button>
    );
  }
}

// // 定义参数类型
// ImportExportExcel.propTypes = {
//   // 模板下载地址
//   // templateHref: PropTypes.string.isRequired,
//   // 上传地址
//   url: PropTypes.string.isRequired,
//   // 导入成功后的回调
//   importSuccessCallback: PropTypes.func,
// };
